from rest_framework import serializers
from .models import KnowledgeGraph, GraphDataSource, GraphDataSourceTable, UnstructuredFile

class KnowledgeGraphListSerializer(serializers.ModelSerializer):
    """
    图谱列表序列化器
    """
    graph_type_display = serializers.CharField(source='get_graph_type_display', read_only=True)
    status_display = serializers.CharField(source='get_status_display', read_only=True)

    class Meta:
        model = KnowledgeGraph
        fields = ['id', 'name', 'graph_type', 'graph_type_display', 'created_at', 'status', 'status_display']


class KnowledgeGraphCreateSerializer(serializers.ModelSerializer):
    """
    图谱创建序列化器
    """

    class Meta:
        model = KnowledgeGraph
        fields = ['id', 'name', 'graph_type', 'data_source', 'created_at', 'status']


class GraphDataSourceSerializer(serializers.ModelSerializer):
    """
    数据源序列化器
    """
    class Meta:
        model = GraphDataSource
        fields = ['db_type', 'db_name', 'username', 'password', 'host', 'port']


class GraphDataSourceTableCheckSerializer(serializers.Serializer):
    """
    数据源构建表序列化器
    """
    table_name = serializers.ListField(
        child=serializers.CharField(max_length=100),
        required=True  # 如果这个字段不是必填项
    )

    commit = serializers.ListField(
        child=serializers.CharField(max_length=100, allow_blank=True, default=''),
        required=False,  # 如果这个字段不是必填项
        allow_null=True,  # 允许该字段为空字符串
    )


class GraphDataSourceTableSerializer(serializers.ModelSerializer):
    """
    数据源构建表序列化器
    """
    table_name = serializers.CharField(max_length=100)
    commit = serializers.CharField(max_length=100, required=False, allow_null=True, default='')

    class Meta:
        model = GraphDataSourceTable
        fields = ['table_name', 'commit', 'graph']

class UnstructuredFileSerializer(serializers.ModelSerializer):
    """
    非结构化文件序列化器
    """
    class Meta:
        model = UnstructuredFile
        fields = ['file_name', 'file_type', 'uploaded_at']


class KnowledgeGraphCreateSerializer(serializers.ModelSerializer):
    """
    创建图谱序列化器
    """
    data_source = GraphDataSourceSerializer(required=False)
    
    class Meta:
        model = KnowledgeGraph
        fields = ['name', 'graph_type', 'data_source']

    def create(self, validated_data):
        data_source_data = validated_data.pop('data_source', None)
        graph = KnowledgeGraph.objects.create(**validated_data)

        if data_source_data:
            GraphDataSource.objects.create(graph=graph, **data_source_data)
            
        return graph


class TestConnectionSerializer(serializers.Serializer):
    graph_type = serializers.ChoiceField(choices=['structured'], required=True)
    data_source = GraphDataSourceSerializer(required=True)